/**
 * 新增-入库明细表js
 */
$(function () {
	$('#select2Id').selectBindEx({
		url: "/sys/macro/value?value=供应商",
		async: true,
		text: 'name',
		value: 'macroId',
		placeholder: '请选择供应商...',
		selected: '',
		allowClear: false,
		theme: "bootstrap",
		language: "zh-CN",
		change: function(){}
	});

	$('#select2Type').selectBindEx({
		url: "/sys/macro/value?value=入库类型",
		async: true,
		text: 'name',
		value: 'macroId',
		placeholder: '请选择入库类型...',
		selected: '',
		allowClear: false,
		theme: "bootstrap",
		language: "zh-CN",
		change: function(){}
	});

	$('#select2Dept').selectBindEx({
		url: "/sys/macro/value?value=库房",
		async: true,
		text: 'name',
		value: 'macroId',
		placeholder: '请选择入库库房...',
		selected: '',
		allowClear: false,
		theme: "bootstrap",
		language: "zh-CN",
		change: function(){}
	});

	$('#select2Item').selectBindEx({
		url: "/sys/macro/value?value=项目",
		async: true,
		text: 'name',
		value: 'macroId',
		placeholder: '请选择项目...',
		selected: '',
		allowClear: false,
		theme: "bootstrap",
		language: "zh-CN",
		change: function(){}
	});

	var table = $("#tb_product");
	var oTable = table.DataTable({
		"bProcessing":true,
		"sPaginationType":"full_numbers",
		"oLanguage":{
			"sLengthMenu":"显示 _MENU_ 条记录",
			"sZeroRecords":"没有检索到数据",
			"sInfo":"当前数据为从 _START_ to _END_ 条数据；总共有 _TOTAL_ 条记录",
			"sInfoEmpty":"没有数据",
			"sProcessing":"正在加载数据......",
			"sSearch":"查询",
			"sInfoFiltered": "(过滤自 _MAX_ 条记录)",
			"oPaginate":{
				"sFirst":"首页",
				"sPrevious":"前页",
				"sNext":"后页",
				"sLast":"尾页"
			}
		}
	});

	var nNew = false;
	var nEditing = false;
	var addRow = 1;

	//添加一行
	$('#detail_editable_1_new').on('click', function (e) {
		e.preventDefault();
		if (nNew && nEditing) {
			if (confirm("前面记录没有保存，您是否需要保存?")) {
				saveRow(oTable, nEditing);
				//$(nEditing).find("td:first").html("未保存");
				nEditing = null;
				nNew = false;
			} else {
				addRow--;
				oTable.fnDeleteRow(nEditing);
				nEditing = null;
				nNew = false;
				return;
			}
		}

		//添加一条新的记录
		var aiNew = oTable.fnAddData([addRow++, '', '', '', '', '', '', '', '', '', '']);
		var nRow = oTable.fnGetNodes(aiNew[0]);
		editRow(oTable, nRow);
		nEditing = nRow;
		nNew = true;
	});

	//删除操作
	table.on('click', '.delete', function (e) {
		e.preventDefault();
		/*if (confirm("您确认要删除该行记录吗?") === false) {
			return;
		}*/
		//获取上一级tr行的数据
		var nRow = $(this).parents('tr')[0];
		var aData = oTable.fnGetData(nRow);

		var found = false;
		$.each(objList, function (i, item) {
			if (item["seq"] === aData[0]) {
				found = true;
				objList.splice(i, 1);
			}
		});
		oTable.fnDeleteRow(nRow);
	});

	//取消操作
	table.on('click', '.cancel', function (e) {
		e.preventDefault();
		addRow--;
		if (nNew) {
			oTable.fnDeleteRow(nEditing);
			nEditing = null;
			nNew = false;
		} else {
			restoreRow(oTable, nEditing);
			nEditing = null;
		}
	});

	//编辑操作
	table.on('click', '.edit', function (e) {
		e.preventDefault();
		nNew = false;
		/*获取所击连接的行对象*/
		var nRow = $(this).parents('tr')[0];
		if (nEditing !== null && nEditing !== nRow) {
			/* 当前正在编辑 - 但不是此行 - 在继续编辑模式之前恢复旧版 */
			restoreRow(oTable, nEditing);
			editRow(oTable, nRow);
			nEditing = nRow;
		} else if (nEditing === nRow && this.innerHTML === "保存") {
			/* 编辑该行，并准备保存记录 */
			if (saveRow(oTable, nEditing) !== false) {
				nEditing = null;
			}
		} else {
			/* No edit in progress - let's start one */
			editRow(oTable, nRow);
			nEditing = nRow;
		}
	});
});



//编辑行
function editRow(oTable, nRow) {
	var aData = oTable.fnGetData(nRow);
	var jqTds = $('>td', nRow);
	jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '" readonly>';
	jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '" readonly>';
	jqTds[2].innerHTML = '<input type="text" class="form-control input-small" onclick="selectAssets(this)" value="' + aData[2] + '">';
	jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '" readonly>';
	jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[4] + '" readonly>';
	jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[5] + '" readonly>';
	jqTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[6] + '">';
	jqTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[7] + '">';
	jqTds[8].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[8] + '" readonly>';
	jqTds[9].innerHTML = '<a class="edit" href="">保存</a>';
	jqTds[10].innerHTML = '<a class="cancel" href="">取消</a>';
}

var objList = [];
//保存行数据，切换到普通模式
function saveRow(oTable, nRow) {
	var jqInputs = $('input', nRow);

	var inBoundNum = jqInputs[6].value;
	//校验入库数量
	if (isNaN(inBoundNum)) {
		dialogMsg('入库数量必须是数字', 'error');
		return false;
	}
	var quantity = parseInt(inBoundNum);
	if (isNaN(quantity) || quantity <= 0) {
		dialogMsg('入库数量必须是正整数', 'error');
		return false;
	}

	//校验进货单价
	if (isNaN(jqInputs[7].value)) {
		dialogMsg('进货单价必须是数字', 'error');
		return false;
	}
	var unitPrice = parseFloat(jqInputs[7].value);
	if (isNaN(unitPrice) || unitPrice <= 0) {
		dialogMsg('进货单价必须是正数', 'error');
		return false;
	}

	//更新行中每个input的值
	oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
	oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
	oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
	oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
	oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
	oTable.fnUpdate(jqInputs[5].value, nRow, 5, false);
	oTable.fnUpdate(jqInputs[6].value, nRow, 6, false);
	oTable.fnUpdate(jqInputs[7].value, nRow, 7, false);
	oTable.fnUpdate(jqInputs[6].value * jqInputs[7].value, nRow, 8, false);
	oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 9, false);
	oTable.fnUpdate('<a class="delete" href="">删除</a>', nRow, 10, false);
	oTable.fnDraw();
}

//重置行数据
function restoreRow(oTable, nRow) {
	editRow(oTable, nRow);
	saveRow(oTable, nRow);
}

//选择商品名称
function selectAssets(obj) {
	top.layer.open({
		type : 2,
		id : 'layerFormProductList',
		title : '商品列表',
		closeBtn : 1,
		anim: -1,
		isOutAnim: false,
		shadeClose : false,
		shade : 0.3,
		area: ['920px', '620px'],
		content: ['base/product/listForInBound.html'],
		btn: ['确定', '取消'],
		success: function(){
		},
		yes: function(){
			//使用getSelections即可获得，row是json格式的数据
			var rowSelected = parent.layerFormProductList.$("#dataGridForInBound")
				.bootstrapTable('getSelections', function (row) {return row;});
			if(rowSelected.length === 1){
				obj.parentElement.parentElement.childNodes[1].childNodes[0].value = rowSelected[0].id;
				obj.value = rowSelected[0].name;
				obj.parentElement.nextElementSibling.childNodes[0].value = rowSelected[0].specification;
				obj.parentElement.nextElementSibling.nextElementSibling.childNodes[0].value = rowSelected[0].unit;
				obj.parentElement.nextElementSibling.nextElementSibling.nextElementSibling.childNodes[0].value = rowSelected[0].manufacturer;
			}else{
				dialogMsg("请选中一行");
			}
			var index=parent.layer.getFrameIndex('layerFormProductList'); //获取当前窗口的name
			parent.layer.close(index);		//关闭窗口
		}
	});
}

//获取表格的数据，并返回对象列表
function GetData(oTable) {
	var list = [];
	var trs = oTable.fnGetNodes();
	for (var i = 0; i < trs.length; i++) {
		var data = oTable.fnGetData(trs[i]);//获取指定行的数据

		var obj = {};
		obj["productId"] = data[1];
		obj["name"] = data[2];
		obj["quantity"] = data[6];
		obj["unitPrice"] = data[7];
		obj["totalPrice"] = data[8];
		list.push(obj);
	}
	return list;
}

var vm = new Vue({
	el:'#dpLTE',
	data: {
		inBound: {
			id: 0,
			inBoundNumber: new Date().getTime(),
			inBoundPeople: {},
			supplier: {},
			inTypeCode: {},
			inDeptCode: {},
			inItemCode: {},
			inBoundDetailsEntities: []
		},
	},
	methods : {
		acceptClick: function() {
			vm.inBound.supplier = $("#select2Id option:selected").val();
			vm.inBound.inTypeCode = $("#select2Type option:selected").val();
			vm.inBound.inDeptCode = $("#select2Dept option:selected").val();
			vm.inBound.inItemCode = $("#select2Item option:selected").val();
			vm.inBound.inBoundDetailsEntities = GetData($("#tb_product").DataTable());
		    $.SaveForm({
		    	url: '../../inbound/saveInBoundAndDetails?_' + $.now(),
		    	param: vm.inBound,
		    	success: function(data) {
		    		$.currentIframe().vm.load();
		    	}
		    });
		},
		getUser: function () {
			$.getJSON("/sys/user/info?_" + $.now(), function (r) {
				vm.inBound.inBoundPeople = r.user.realName;
			});
		},
	}
});
vm.getUser();
